package org.example.auth.config.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.example.api.system.RemoteTenantService;
import org.example.api.system.domain.vo.RemoteTenantVo;
import org.example.auth.domain.EmailCodeBody;
import org.example.auth.domain.MobileCodeBody;
import org.example.auth.domain.SocialLoginBody;
import org.example.auth.domain.vo.LoginTenantVo;
import org.example.auth.domain.vo.TenantListVo;
import org.example.common.core.domain.R;
import org.example.common.core.utils.MapstructUtils;
import org.example.common.core.utils.StreamUtils;
import org.example.common.core.utils.StringUtils;
import org.example.common.redis.utils.LoginHelper;
import org.example.common.social.config.properties.SocialLoginConfigProperties;
import org.example.common.social.config.properties.SocialProperties;
import org.example.common.social.utils.SocialUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;
import java.util.List;

/**
 *第三方登录控制器
 */
@RestController
@RequiredArgsConstructor
public class AuthController {

    private final SocialProperties socialProperties;

    @DubboReference
    private RemoteTenantService remoteTenantService;

    private final static String LOGINURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**
     * 发送短信验证码
     * @param mobile
     * @return
     */
    @PostMapping("/mobile/code")
    public R mobileCode(@RequestBody MobileCodeBody mobile){

        return R.ok();
    }

    /**
     *发送邮箱验证码
     * @param email
     * @return
     */
    @PostMapping("/email/code")
    public R emailCode(@RequestBody EmailCodeBody email){



        return R.ok();
    }


    /**
     * 第三方登录请求
     *
     * @param source 登录来源
     * @return 结果
     */
    @GetMapping("/binding/{source}")
    public R authBinding(@PathVariable("source") String source) {
        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
        if (ObjectUtil.isNull(obj)) {
            return R.fail(source + "平台账号暂不支持");
        }
        AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        return R.ok("操作成功", authorizeUrl);
    }

    /**
     * 第三方登录回调业务处理 绑定授权
     *
     * @param loginBody 请求体
     * @return 结果
     */
    @PostMapping("/social/callback")
    public R socialCallback(SocialLoginBody loginBody) {
//        // 获取第三方登录信息
        AuthResponse<AuthUser> response = SocialUtils.loginAuth(
                loginBody.getSource(), loginBody.getSocialCode(),
                loginBody.getSocialState(), socialProperties);
        AuthUser authUserData = response.getData();
        // 判断授权响应是否成功
        if (!response.ok()) {
            return R.fail(response.getMsg());
        }
//        sysLoginService.socialRegister(authUserData);
        return R.ok();
    }


    /**
     * 取消授权
     *
     * @param socialId socialId
     */
    @DeleteMapping(value = "/unlock/{socialId}")
    public R unlockSocial(@PathVariable Long socialId) {
//        Boolean rows = remoteSocialService.deleteWithValidById(socialId);
        Boolean rows = true;
        return rows ? R.ok() : R.fail("取消授权失败");
    }


    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @GetMapping("/tenant/list")
    public R<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
        List<RemoteTenantVo> tenantList = remoteTenantService.queryList();
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        // 获取域名
        String host;
        String referer = request.getHeader("referer");
        if (StringUtils.isNotBlank(referer)) {
            // 这里从referer中取值是为了本地使用hosts添加虚拟域名，方便本地环境调试
            host = referer.split("//")[1].split("/")[0];
        } else {
            host = new URL(request.getRequestURL().toString()).getHost();
        }
        // 根据域名进行筛选
        List<TenantListVo> list = StreamUtils.filter(voList, vo ->
                StringUtils.equals(vo.getDomain(), host));
        // 返回对象
        LoginTenantVo vo = new LoginTenantVo();
        vo.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        vo.setTenantEnabled(true);
        return R.ok(vo);
    }



    @GetMapping("/authLogout")
    public R logout() {
        LoginHelper.logout();
        return R.ok("操作成功");
    }



}
